<form id="ndInterval" name="ndInterval" method="POST" action="#" class="well well-large form-inline">
    <fieldset>
        <legend>Проверка данных</legend>

        <?php /*
        <div class="control-group">
            <p>Интервал времени:</p>
            <label for="from_date" class="control-label">с <input type="text" value="2010-01-01" name="from_date" id="from_date" class="input-medium hasDatepicker"> </label>
            <label for="to_date" class="control-label"> по <input type="text" value="2012-06-28" name="to_date" id="to_date" class="input-medium hasDatepicker"> </label>

            <button class="btn btn-primary" type="submit"><i class="icon-ok-sign icon-white"></i> Показать</button>
        </div>
         */?>


        <div class="control-group" id="nd-buttons">
            <div  id="ndSearchProgress" >
                <p class="help-block">Поиск...</p>
                <div class="progress progress-info" style="height: 5px;" title="0%">
                    <div class="bar" style=" width: 0%;"></div>
                </div>
            </div>

            <div class="span4" style="white-space:nowrap;">
                <button id="btn-yesterday" class="btn btn-info" type="button" days="1"><i class="icon-calendar icon-white"></i> За вчера</button>
                <button id="btn-week" class="btn btn-info" type="button" days="7"><i class="icon-calendar icon-white"></i> За 7 дней</button>
                <button id="btn-month" class="btn btn-info" type="button" days="30"><i class="icon-calendar icon-white"></i> За 30 дней</button>
            </div>


        </div>


    </fieldset>
</form>


<?php
$e = Arr::getValue($params, 'error', false);

if ($e) {?>
<div class="alert alert-danger"> <?php echo $e; ?> </div>
<?php } ?>

<div id="div-noData">
    Нажмите одну из кнопок, чтобы начать поиск объектов в соответствующем интервале времени
</div>



<script>
    var ndObjData = {};
    var cncData = <?php echo json_encode(ConceptionsCollection::allRowsById()); ?>;
    cncData[0] = {id: 0, name: 'Концепция не указана'};
    var sut = 60 * 60 * 24; //секунд в сутках

    /**
     * Возвращает TS момента времени "текущее время плюс days суток"
     **/
    function getRelTimestamp(days) {
        days = parseInt(days) || 1;

        var ts_sec = Math.round((new Date()).getTime()/1000);
        return ts_sec + sut*days;
    }


    function getConceptionUL(cncId) {
        cncId = cncId || 0;
        var cnc = false;
        if (cncData.hasOwnProperty(cncId)) cnc = cncData[cncId];
        if (!cnc) {
            cncId = 0;
            cnc = cncData[cncId];
        }

        var cont = $('#cncCont-'+cncId);
        if (!cont.length) {
            cont = $('<div>').attr({id: 'cncCont-'+cncId}).css({display:'none'});
            cont.append($('<h3>').html(cnc.name)).
                 append('<hr style="margin-top:3px;">').
                 append($('<ul>').addClass('thumbnails'));
            cont.appendTo(Elm.ndUL).show('300');
        }

        return cont.find('ul.thumbnails');
    }



    function objCellDetails(elm) {
        var itd = elm.id.replace('mon-objCell-', '');
        itd = itd.split('_');
        var id = itd[0];
        var the_date = itd[1];

        var obj = {};
        var value;
        if (ndObjData.hasOwnProperty(id) && ndObjData[id]) obj = ndObjData[id];
        obj.the_date = the_date;

        var detailsContent = $('#objCellAlert-tmpl').html();

        for (var prop in obj) {
            if (!obj.hasOwnProperty(prop)) continue;
            value = obj[prop]?  obj[prop] : '';
            detailsContent = detailsContent.gReplace('{%'+prop+'%}', value);
        }


        ovlAlert(detailsContent);

        var form = document.forms['reasonForm_'+obj.id];

        var clearByChange = [];
        clearByChange['reason'+obj.id] = $('#manual_value'+obj.id);
        clearByChange['manual_value'+obj.id] = $('#reason'+obj.id);

        $(form).find('input').keydown(function(){
            if (clearByChange.hasOwnProperty(this.id)) clearByChange[this.id].val('');
        });


        var btnreset = $('#reason-'+obj.id+'-cancel').click(function() {ovlClose();});
        var btnsubmit = $('#reason-'+obj.id+'-submit').click(function() {

            var val = $('#manual_value'+obj.id).val();
            if (val && /[^0-9.,]/gi.test(val)) {
                uiAlert('Некорректное значение','Error');
                return;
            }
            $('#manual_value'+obj.id).val(val.gReplace(',', '.'));

            btnreset.attr('disabled', 'disabled');
            btnsubmit.attr('disabled', 'disabled');

            var send = $(form).serialize();
            jsonRequest(
                'reasons.php',
                send,

                function(data) {
                    if(!checkSession(data)) {
                        btnreset.removeAttr('disabled');
                        btnsubmit.removeAttr('disabled');
                        Elm.loginFormModal.dialog('open');
                        return;
                    }
                    if (!data.state) {
                        uiAlert(data.message,'Error');
                        btnreset.removeAttr('disabled');
                        btnsubmit.removeAttr('disabled');
                        return;
                    }

                    if (data.hasOwnProperty('relocate') && data.relocate) window.location.assign(data.relocate);
                    else {
                        //uiAlert('Изменения сохранены','Информация');
                        $(elm).hide(500);
                        ovlClose();
                    }
                },

                function() {
                    uiAlert('Ошибка соединения','Error');
                }
            );
        });

    }


    function loadNDObjects(input_params) {
        var params = {
            from_time   : 0,
            from_id     : 0,
            start_time  : 0,
            start_id    : 0,
            action      : '<?php echo ACTIONS::MONITOR_NDLIST; ?>'
        };

        input_params = input_params || {};

        $.extend(params, input_params);

        jsonRequest(
                'monitoring.php?ndObjects',
                params,

                function(data) {
                    if(!checkSession(data)) {
                        Elm.loginFormModal.dialog('open');
                        Elm.loginFormModal.successCallback = function(){
                            loadNDObjects(params);
                        };
                        return;
                    }
                    if (data.hasOwnProperty('relocate') && data.relocate) {
                        window.location.assign(data.relocate);
                    }
                    if (!data.state) {
                        uiAlert(data.message,'Error');
                        Elm.ndProgressBar.hide(500);
                        return;
                    }

                    //console.log(data);
                    updateNDProgress(data.response_data.progress);
                    $.extend(ndObjData, data.response_data.ndObjData);

                    var found = data.response_data.found;

                    for (var i in found) {
                        if (!found.hasOwnProperty(i)) continue;
                        var objData = found[i];
                        var oContent = $('#objCell-tmpl').html();
                        var obj = ndObjData[objData.id];
                        obj.the_date = objData.date;

                        for (var prop in obj) {
                            if (!obj.hasOwnProperty(prop)) continue;
                            value = obj[prop]?  obj[prop] : '';
                            oContent = oContent.gReplace('{%'+prop+'%}', value);
                        }

                        var cnccont = getConceptionUL(obj.conception);
                        if (!cnccont) cnccont = Elm.ndUL;
                        cnccont.append(oContent);
                        $('#mon-objCell-'+obj.id+'_'+obj.the_date).show(500);
                    }

                    if (!data.response_data.done) {
                        if (
                                params.start_id == data.response_data.last_id
                                && params.start_time >= data.response_data.last_time
                        ) {
                                //Зацикливание
                                console.log('FIND: infinite cycle on obj_id '+params.start_id + ' - date ' + data.response_data.last_date);
                                params.start_id++;
                                params.start_time = params.from_time;
                        }
                        else {
                            params.start_id = data.response_data.last_id;
                            params.start_time = data.response_data.last_time;
                        }

                        setTimeout(function() {loadNDObjects(params);}, 300);
                    }
                    else setTimeout(function() {
                        hideNDProgress();
                        ndButtonsEnable();
                    }, 3000);

                },

                function() { uiAlert('Ошибка соединения','Error'); }
        );
    }



    function showNDProgress() {
        updateNDProgress(0);
        Elm.ndProgressBar.show(200);
    }

    function updateNDProgress(percent) {
        Elm.ndProgressLine.css({width: percent*1+'%'});
        Elm.ndProgressBar.find('.progress').attr({title: percent*1+'%'});
    }

    function hideNDProgress() {
        Elm.ndProgressBar.hide(500);
    }



    function ndButtonsDisable() {
        Elm.ndButtons.attr({disabled:'disabled'});
    }

    function ndButtonsEnable() {
        Elm.ndButtons.removeAttr('disabled');
    }

    function ndButtonsDefault(btns) {
        btns.attr('class', 'btn btn-info');
        //btns.find('i.icon').addClass('icon-white');
    }

    function ndButtonsActive(btns) {
        btns.attr('class', 'btn btn-primary');
    }


    $(function() {
        Elm.ndProgressBar = $('#ndSearchProgress');
        Elm.ndProgressLine = Elm.ndProgressBar.find('.bar');
        Elm.ndUL = $('#div-noData');

        Elm.ndButtons = $('#nd-buttons button');

        Elm.ndButtons.click(function(){
            Elm.ndUL.empty();
            showNDProgress();
            var sthis = $(this);

            ndButtonsDefault(Elm.ndButtons);
            ndButtonsActive(sthis);
            ndButtonsDisable();

            var days = sthis.attr('days') * -1;
            var start = getRelTimestamp(days);
            loadNDObjects({
                from_time   : start,
                start_time  : start
            });
        });




        $('body').css({'overflow-y':'scroll'});

        /*$('#ul-noData li.noDataCell').click(function() {
            objCellDetails(this);
        });*/
    });

</script>

<ul id="objCell-tmpl" class="hidden">
    <li id="mon-objCell-{%id%}_{%the_date%}" class="span3 thumbnail noDataCell objCell objtype_{%obj_type%}" style="display:none;" onclick="objCellDetails(this);return false;">
        <span class="cell-date" >{%the_date%}</span>
        <div class="cell-name">{%obj_name%}</div>
        <div class="objCell-reason">Нет данных</div>
    </li>
</ul>

<div id="objCellAlert-tmpl" class="hidden">

    <div  id="objCellAlert-{%id%}_{%the_date%}" class="well well-small objCell-info">
        <h4 class="pull-right">{%the_date%}</h4>
        <h4>{%obj_name%}</h4>
        <div style="margin:10px 0px 5px; text-align: justify;">{%address%}</div>

        <form class="form-inline well well-large" action="" method="POST" name="reasonForm_{%id%}" id="reasonForm_{%id%}">
            <fieldset>

                <input type="hidden" name="action" id="action" value="<?php echo ACTIONS::REASON_ADD; ?>">
                <input type="hidden" name="trc_id" id="trc_id{%id%}" value="{%id%}">
                <input type="hidden" name="to_date" id="to_date{%id%}" value="{%the_date%}">

                <div class="control-group">
                    <label class="control-label" for="reason">Причина отказа</label>
                    <div class="controls">
                        <input type="text" class="input-large" id="reason{%id%}" name="reason" value="">
                    </div>
                </div>

                <div class="control-group">
                    <label class="control-label" for="manual_value">Значение</label>
                    <div class="controls">
                        <input type="text" class="input-large" id="manual_value{%id%}" name="manual_value" value="">
                    </div>
                </div>

                <div class="form-actions">
                    <button type="button" class="btn btn-primary" id="reason-{%id%}-submit"><i class="icon-ok icon-white"></i> Сохранить</button>
                    <button type="button" class="btn btn-danger" id="reason-{%id%}-cancel"><i class="icon-remove icon-white"></i> Отменить</button>
                </div>
            </fieldset>
        </form>

    </div>
</div>

